package com.dz.scrm.mvp.ui.fragment

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.telephony.SubscriptionManager
import android.telephony.TelephonyManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat.getSystemService
import androidx.recyclerview.widget.GridLayoutManager
import butterknife.OnClick
import com.dz.scrm.R
import com.dz.scrm.app.adpter.KeyBoardAdpter
import com.dz.scrm.app.config.WHAT_PHONE_NAME
import com.dz.scrm.mvp.model.entity.LoginCompanyBean
import com.dz.scrm.mvp.presenter.DZPresent
import com.dz.scrm.utils.StringUtils
import com.dz.scrm.utils.callPhone
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.fragment_call_phone_layout.*
import me.jessyan.art.base.BaseFragment
import me.jessyan.art.mvp.IView
import me.jessyan.art.mvp.Message
import me.jessyan.art.utils.ArtUtils
import org.litepal.LitePalApplication

/**
 * 作者：fanda
 * 日期：2021/4/23 11:51
 * 描述：打电话
 */
class PhoneCallFragment : BaseFragment<DZPresent>(), KeyBoardAdpter.itemOnClickListener, IView,
    View.OnClickListener {

    private var dataList =
        listOf("", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ", "*", "0", "#")
    private lateinit var adpter: KeyBoardAdpter

    companion object {
        @JvmStatic
        fun getInstance(): PhoneCallFragment {
            return PhoneCallFragment().apply {
            }
        }
    }

    override fun initView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return inflater.inflate(R.layout.fragment_call_phone_layout, container, false)
    }

    override fun initData(savedInstanceState: Bundle?) {
        adpter = KeyBoardAdpter(activity, dataList, this)
        if (checkPhone() == 1) {//单卡
            onePhoneLayout.visibility = View.VISIBLE
            group_one.visibility = View.INVISIBLE
        } else if (checkPhone() == 2) {//双卡
            onePhoneLayout.visibility = View.INVISIBLE
            group_one.visibility = View.VISIBLE
        }
        phoneNumRecyclerView.layoutManager = GridLayoutManager(activity, 3)
        phoneNumRecyclerView.adapter = adpter

    }

    override fun obtainPresenter() =
        DZPresent(ArtUtils.obtainAppComponentFromContext(mContext), RxPermissions(this))

    override fun setData(data: Any?) {
    }

    @SuppressLint("SetTextI18n")
    override fun onClick(position: Int) {
        if (position < 9) {
            tv_phone_num.text = tv_phone_num.text.toString() + (position + 1).toString() + ""
        } else {
            tv_phone_num.text = tv_phone_num.text.toString() + dataList.get(position) + ""
        }
        tv_phone_name.visibility = View.VISIBLE
    }

    override fun showLoading() {
    }

    override fun handleMessage(message: Message) {
        when (message.what) {
            WHAT_PHONE_NAME -> {
                //登录成功
                val loginBean = message.obj as LoginCompanyBean?
                if (!StringUtils.isEmpty(loginBean?.customerName)) {
                    tv_phone_num.text = loginBean!!.customerName
                }
            }
        }
    }

    override fun hideLoading() {
    }

    override fun showMessage(message: String) {
        ArtUtils.snackbarText(message)
    }

    /***
     * 刷新UI
     */
    fun refreshView() {
        if (checkPhone() == 1) {
            onePhoneLayout.visibility = View.VISIBLE
            group_one.visibility = View.INVISIBLE
        } else if (checkPhone() == 2) {
            onePhoneLayout.visibility = View.INVISIBLE
            group_one.visibility = View.VISIBLE
        }
    }

    /***
     * 清除面板电话号码
     */
    fun clearPhoneNum() {
        tv_phone_num.text = ""
        tv_phone_name.visibility = View.INVISIBLE
    }

    /***
     * 获取sim数量
     */
    @SuppressLint("MissingPermission")
    fun checkPhone(): Int {
        var simNun = 1;
//        val tm = getSystemService(mContext, TelephonyManager::class.java)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
//            String NAME = tm.getSimCarrierIdName().toString();
            //获取手机卡槽数量
//            Log.e("HH", "name -11111 > " + "; num = " + tm!!.phoneCount)
            //获取当前SIM卡数量
            simNun =
                SubscriptionManager.from(LitePalApplication.getContext()).activeSubscriptionInfoCount
        }
        return simNun
    }

    @OnClick(
        R.id.img_bload,
        R.id.onePhone_bload_Layout,
        R.id.tv_sim_one,
        R.id.tv_sim_two,
        R.id.imgKeyBorad,
        R.id.imgCallPhone,
        R.id.imgOnePhoneCall,
        R.id.img_onePhone_closeLyout,
        R.id.img_closeLyout
    )
    override fun onClick(v: View?) {
        if (v == img_bload || v == onePhone_bload_Layout) {
            //键盘显示隐藏
            if (phoneLayout.visibility == View.VISIBLE) {
                phoneLayout.visibility = View.INVISIBLE
            }
            imgKeyBorad.visibility = View.VISIBLE
        } else if (v == tv_sim_one) {
            //卡1
            callPhone(1)
        } else if (v == tv_sim_two) {
            //卡2
            callPhone(2)
        } else if (v == imgCallPhone || v == imgOnePhoneCall) {
            //单卡
            if (tv_phone_num.text.isNotEmpty()) {
                activity?.callPhone(tv_phone_num.text.toString())
            }
        } else if (v == img_onePhone_closeLyout || v == img_closeLyout) {
            //删除
            if (tv_phone_num.text.toString().isNotEmpty()) {
                tv_phone_num.text =
                    tv_phone_num.text.toString().take(tv_phone_num.text.toString().length - 1)
            }
            if (tv_phone_num.text.isEmpty()) {
                tv_phone_name.visibility = View.INVISIBLE
            }
        } else if (v == imgKeyBorad) {
            phoneLayout.visibility = View.VISIBLE
            imgKeyBorad.visibility = View.GONE
        }
    }


    /***
     * 拨打电话
     */
    fun callPhone(num: Int) {
        if (checkPhone() == 0) {
            ArtUtils.snackbarText("请插入电话卡")
        } else {
            if (tv_phone_num.text.isNotEmpty()) {
//                activity?.callPhone(tv_phone_num.text.toString(), 2)
                activity?.callPhone(tv_phone_num.text.toString())
            }
        }
    }

}